package com.hebtu.helper.modules.sys.controller;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import com.hebtu.helper.common.constants.Constant;
import com.hebtu.helper.common.exception.HelperException;
import com.hebtu.helper.common.utils.H;
import com.hebtu.helper.modules.sys.entity.SysUserEntity;
import com.hebtu.helper.modules.sys.service.SysUserService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Base64;


/**
 * 登陆相关
 * @author YKF
 * @date 2019/5/22 23:20
 */
@Controller
public class SysLoginController {

    private static final Logger log = LoggerFactory.getLogger(SysLoginController.class);

    @Autowired
    private Producer producer;
    @Autowired
    private SysUserService sysUserService;
    /**
     * 验证码
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping("/captcha.jpg")
    public void captcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
        //生成文字验证码
        String text = producer.createText();
        //生成图片验证码
        BufferedImage image = producer.createImage(text);

        //保存到session
        request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, text);

        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
    }

    /**
     * 登录
     */
    @ResponseBody
    @RequestMapping(value = "/sys/login", method = RequestMethod.POST)
    public H login(HttpServletRequest request, String username, String password, String captcha) {
        if (username.isEmpty()) {
            return H.error( "姓名不能为空");
        }
        if (password.isEmpty()) {
            return H.error("密码不能为空");
        }
        if (captcha.isEmpty()) {
            return H.error("验证码不能为空");
        }
        String kaptcha = (String) request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
        if (StringUtils.isBlank(kaptcha)) {
            throw new HelperException("验证码已失效", 501);
        }
        if (!captcha.equalsIgnoreCase(kaptcha)) {
            request.getSession().removeAttribute(Constants.KAPTCHA_SESSION_KEY);
            return H.error(501, "验证码不正确");
        }
        H h = H.success("登录成功！");
        SysUserEntity sysLoginEntity = sysUserService.selectByUsername(username);
        if (sysLoginEntity == null) {
            return H.error("账号不存在");
        }
        if (sysLoginEntity.getState()==0 ||sysLoginEntity.getState()==2){
            return H.error("账号已被停用，请联系教务处");
        }
        //base64加密
        if(!sysLoginEntity.getPassword().equals(Base64.getEncoder().encodeToString(password.getBytes())))
        {
            return H.error("密码错误");
        }
        sysLoginEntity.setPassword(null);
        request.getSession().setAttribute(Constant.SYS_KEY, sysLoginEntity);
        log.info("username :{} 登录成功!!", username);
        return h;
    }

    /**
     * 退出
     */
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public String logout(HttpSession session) {
        session.removeAttribute(Constant.SYS_KEY);
        return "redirect:login.html";
    }

    public static void main(String[] args) {
        String password = "admin";
        System.out.println(Base64.getEncoder().encodeToString(password.getBytes()));
    }
}
